from rest_framework.viewsets import ModelViewSet
from .serializers import MenuItemSerializer, PositionItemSerializer, RoleSerializer, LogSerializer
from utils.common_response import APIResponse
from utils.common_mixins import ResponseMixin
from rest_framework.decorators import action
from backend.models import Menu
from .filter import MenuFilter
from school.models import Role, Position
from .models import BackendLog
from rest_framework.filters import SearchFilter, OrderingFilter
from user_agents import parse
from django.conf import settings
from django.db.models.functions import ExtractDay, ExtractMonth
from django.db.models import Count
from utils.common_pagination import CommonPageNumberPagination


class LogView(ResponseMixin, ModelViewSet):
    queryset = BackendLog.objects.all().order_by('-create_time')
    serializer_class = LogSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['user', 'view', 'addr']
    ordering_fields = ['status']
    pagination_class = CommonPageNumberPagination

    @action(methods=['post'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()

    def get_queryset(self):
        qs = super().get_queryset()
        user = self.request.user
        if user.is_superuser:
            # 如果是超级管理员，返回所有人的日志
            return qs
        else:
            # 如果不是超级管理员，返回当前用户的日志
            return qs.filter(user=user.id)

    @action(methods=['get'], detail=False)
    def echarts_ua(self, request):
        query_set = self.get_queryset()
        all_data = query_set.values_list('user_agent')
        data = {}
        for item in all_data:
            ua = parse(item[0])
            browser = ua.browser.family
            data[browser] = data.get(browser, 1) + 1
        results = [{'name': key, "value": value} for key, value in data.items()]
        return APIResponse(results=results)

    @action(methods=['get'], detail=False)
    def echarts_date(self, request):
        query_set = self.get_queryset()
        res = query_set.annotate(month=ExtractMonth('create_time'), day=ExtractDay('create_time')
                                 ).values('month', 'day').annotate(count=Count('id')).order_by('month', 'day')
        date_count = [item.get('count') for item in res]
        date = [f"{item.get('month')}-{item.get('day')}" for item in res]
        return APIResponse(date_count=date_count, date=date)


class MenuView(ResponseMixin, ModelViewSet):
    '''
    - 获取菜单
    1：超级管理员返回所有的权限
    2：根据角色返回该角色拥有的权限
    - 权限，根据type分为：
    0：主菜单
    1：子菜单
    2：按钮：按钮有字段permission【子菜单:动作】
    - 涉及的模型表
    user.User下有多对多字段role、position
    backend.Menu
    school.Role
    return:
        code,msg,nav,authority
    '''
    serializer_class = MenuItemSerializer
    queryset = Menu.objects.all().filter(is_delete=False, is_show=True)
    # 过滤类
    filter_backends = [MenuFilter]

    def list(self, request, *args, **kwargs):
        nav = super().list(request, *args, **kwargs)
        role_qs = request.user.role.all().values_list('menu', flat=True)
        if request.user.is_superuser:
            menu_qs = Menu.objects.filter(type=2, is_delete=False, is_show=True)
        else:
            menu_qs = Menu.objects.filter(id__in=role_qs, type=2, is_delete=False, is_show=True)
        # 对权限进行去重
        authority = list(set([menu.permission for menu in menu_qs]))
        return APIResponse(nav=nav.data.get('results'), authority=authority)

    @action(methods=['get'], detail=False)
    def menu_list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return res


class RoleView(ResponseMixin, ModelViewSet):
    '''
    对角色增删改查
    '''
    queryset = Role.objects.all().filter(is_delete=False, is_show=True)
    serializer_class = RoleSerializer
    # 过滤类
    filter_backends = [SearchFilter]
    search_fields = ['name']

    @action(methods=['post'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()


class PositionView(ResponseMixin, ModelViewSet):
    '''
    对部门增删改查
    '''
    queryset = Position.objects.all().filter(is_delete=False, is_show=True)
    serializer_class = PositionItemSerializer
    # 过滤类
    filter_backends = [SearchFilter]
    search_fields = ['name']

    def get_queryset(self):
        qs = super().get_queryset()
        if self.action == 'position_list':
            return qs.filter(parent=None)
        return qs

    @action(methods=['get'], detail=False)
    def position_list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)
